﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Identity;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Identity;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.NewHouse.Controllers
{ 
    [Description("楼盘")]
    public class BuildingsController : BaseController
    { 
        public IBuildingsContract BuildingsContract { set; get; }
        public IAreaContract AreaContract { set; get; }
        public IAgentContract AgentContract { set; get; }
        public IModifyBuildingBrokerageLogContract ModifyBuildingBrokerageLogContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IStaffRolesContract StaffRolesContract { get; set; }
        public IRoleContract RoleContract { get; set; }
        public IBuildingTypeContract BuildingTypeContract { get; set; }
        public IBuildingBuildingTypeContract BuildingBuildingTypeContract { get; set; }
        public IBuildingTopContract BuildingTopContract { get; set; }
        public IDictionaryContract DictionaryContract { get; set; }
        // GET: NewHouse/Buildings
        #region 楼盘列表
        [Description("楼盘-列表")]
        public ActionResult IndexList()
        {
            return View();
        } 
        [HttpPost]
        public ActionResult IndexListAsync(int pageIndex, int pageSize, string search = "", string Province = "", string City = "", string District = "", int WhetherOnline = 0, int PropertyType = 0)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            var query = BuildingsContract.Entities.Where(m => !m.IsDeleted);
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search));
            }
            if (agentid != 0)
            {
                query = query.Where(m => m.AgentID == agentid);
            }
            if (!string.IsNullOrWhiteSpace(Province))
            {
                query = query.Where(m => m.Province.Contains(Province));
            }
            if (!string.IsNullOrWhiteSpace(City))
            {
                query = query.Where(m => m.City.Contains(City));
            }
            if (!string.IsNullOrWhiteSpace(District))
            {
                query = query.Where(m => m.District.Contains(District));
            }
            if (WhetherOnline != 0)
            {
                query = query.Where(m => m.State == WhetherOnline);
            }
            if (PropertyType != 0)
            {
                query = query.Where(m => BuildingBuildingTypeContract.Entities.Count(p => p.BuildingID == m.Id && p.BuildingTypeID == PropertyType) > 0);
            } 
            var data = from q in query
                       select new
                       {
                           Id = q.Id,
                           Name = q.Name,
                           Address = q.Address,
                           SellingPrice = q.SellingPrice,
                           LeasePrice = q.LeasePrice,
                           Remark = q.Remark,
                           BuildingType = from bt in BuildingTypeContract.Entities
                                          join bbt in BuildingBuildingTypeContract.Entities 
                                          on bt.Id equals bbt.BuildingTypeID
                                          where bbt.BuildingID == q.Id
                                          select bt.Name,
                           State = q.State,
                           //Agent = agentid,
                           MediumOfCommunicationStaff = (from taff in StaffContract.Entities where q.MediumOfCommunicationStaffID == taff.Id select taff.Name).FirstOrDefault(),
                           StationedStaff = (from taff in StaffContract.Entities where q.StationedStaffID == taff.Id select taff.Name).FirstOrDefault(),
                           StarTarget = q.StarTarget,
                           StarTargetRemark = q.StarTargetRemark,
                           LetSellType = q.LetSellType,
                           BuildingInfo = q.BuildingInfo,
                           SellingBrokerage = q.SellingBrokerage,
                           CommissionAccount = q.CommissionAccount,
                           Province = (from Area in AreaContract.Entities where q.Province == Area.Id select Area.Name).FirstOrDefault(),
                           City = (from Area in AreaContract.Entities where q.City == Area.Id select Area.Name).FirstOrDefault(),
                           District = (from Area in AreaContract.Entities where q.District == Area.Id select Area.Name).FirstOrDefault(),

                           BuildingTopID = (from btc in BuildingTopContract.Entities where btc.UnionModule == 1 && q.Id == btc.UnionID && !btc.IsDeleted select btc.Id).FirstOrDefault(),
                           BeginTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 1 && q.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.BeginTime).FirstOrDefault(),
                           EndTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 1 && q.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.EndTime).FirstOrDefault(),
                           ShowIndex = (from btc in BuildingTopContract.Entities where btc.UnionModule == 1 && q.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.ShowIndex).FirstOrDefault(),
                           CreatedTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 1 && q.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.CreatedTime).FirstOrDefault(),
                       };
            var total = data.Count();
            
            //默认给一个排序的字段 
            var topCount = BuildingTopContract.Entities.Where(m => m.UnionModule == 1).Count();
            if (topCount > 0)
            {
                data = data.OrderByDescending(m => m.ShowIndex).ThenByDescending(m => m.BeginTime).ThenByDescending(m => m.Id);
            }
            else
            {
                data = data.OrderByDescending(m => m.Id);

            }

            //分页(假如total == 0，则取消分页查询，提高性能)
            data = total > 0 ? data.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : data;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = data.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 楼盘添加
        [Description("楼盘-列表添加")]
        public ActionResult InsertList()
        {

            intorcount();
            return View();
        }

        [HttpPost]
        public ActionResult InsertListAsync(Buildings entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;
            entity.LetSellType = 2;
            entity.State = 1;
            entity.AreaID = entity.District;
            entity.City = AreaContract.GetByKey(entity.AreaID).ParentID;
            entity.Province = AreaContract.GetByKey(entity.City).ParentID;

            #region 所有string为null的赋值""
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.LeasePrice == null)
            {
                entity.LeasePrice = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.BuildingInfo == null)
            {
                entity.BuildingInfo = "";
            }
            if (entity.SellingBrokerage == null)
            {
                entity.SellingBrokerage = "";
            }
            if (entity.LeaseBrokerage == null)
            {
                entity.LeaseBrokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.AveragePrice == null)
            {
                entity.AveragePrice = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.CooperativeHousing == null)
            {
                entity.CooperativeHousing = "";
            }
            if (entity.DevelopersRules == null)
            {
                entity.DevelopersRules = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.FilingRules == null)
            {
                entity.FilingRules = "";
            }
            if (entity.BandSawRules == null)
            {
                entity.BandSawRules = "";
            }
            if (entity.TransactionRules == null)
            {
                entity.TransactionRules = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            if (entity.BuildingTypeID == null)
            {
                entity.HaveProductComparison = "1";
            }
            #endregion

            //开始事务
            BuildingsContract.Repository.UnitOfWork.BeginTransaction();
            try
            {
                var query = BuildingsContract.CheckExists(m => m.Name==entity.Name); 
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的楼盘";
                }
                else
                {
                    var count = BuildingsContract.Insert(entity);

                    var Buildings = Request["BuildingTypeID"];
                    foreach (string item in Buildings.Split(','))
                    {
                        BuildingBuildingTypeContract.Insert(new BuildingBuildingType { BuildingID = entity.Id, BuildingTypeID = Convert.ToInt32(item) });
                    }
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                //事务回滚
                BuildingsContract.Repository.UnitOfWork.Rollback();

                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            //结束事务
            BuildingsContract.Repository.UnitOfWork.Commit();

            return JsonEx(result);
        }
        #endregion 

        #region 楼盘修改
        [Description("楼盘-列表修改")]
        public ActionResult EditList(int id)
        {
            intorcount();
            var entity = BuildingsContract.GetByKey(id);
            entity.BuildingTypeID = String.Join(",", BuildingBuildingTypeContract.Entities.Where(p => p.BuildingID == id).Select(p => p.BuildingTypeID).ToArray());
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }

        [HttpPost]
        public ActionResult EditListAsync(Buildings entity)
        {
            var result = new AjaxResult();
            try
            {
                var cookies = Common.CookiesManagement.GetCookies();
                var ticket = Common.CookiesManagement.GetTicket(cookies);
                var model = Common.CookiesManagement.GetLoginModel(ticket);
                entity.AgentID = model.AgentId;
                #region 所有string为null的赋值""
                if (entity.Address == null)
                {
                    entity.Address = "";
                }
                if (entity.CommissionAccount == null)
                {
                    entity.CommissionAccount = "";
                }
                if (entity.Remark == null)
                {
                    entity.Remark = "";
                }
                if (entity.AreaID == null)
                {
                    entity.AreaID = "";
                }
                if (entity.LeasePrice == null)
                {
                    entity.LeasePrice = "";
                }
                if (entity.StarTarget == null)
                {
                    entity.StarTarget = "";
                }
                if (entity.StarTargetRemark == null)
                {
                    entity.StarTargetRemark = "";
                }
                if (entity.BuildingInfo == null)
                {
                    entity.BuildingInfo = "";
                }
                if (entity.SellingBrokerage == null)
                {
                    entity.SellingBrokerage = "";
                }
                if (entity.LeaseBrokerage == null)
                {
                    entity.LeaseBrokerage = "";
                }
                if (entity.BandSawBrokerage == null)
                {
                    entity.BandSawBrokerage = "";
                }
                if (entity.Developer == null)
                {
                    entity.Developer = "";
                }
                if (entity.DeveloperBrand == null)
                {
                    entity.DeveloperBrand = "";
                }
                if (entity.PropertyManagementCompany == null)
                {
                    entity.PropertyManagementCompany = "";
                }
                if (entity.CoveredArea == null)
                {
                    entity.CoveredArea = "";
                }
                if (entity.TotalHouseholds == null)
                {
                    entity.TotalHouseholds = "";
                }
                if (entity.PlotRatio == null)
                {
                    entity.PlotRatio = "";
                }
                if (entity.GreeningRatio == null)
                {
                    entity.GreeningRatio = "";
                }
                if (entity.CarNumber == null)
                {
                    entity.CarNumber = "";
                }
                if (entity.ParkingRatio == null)
                {
                    entity.ParkingRatio = "";
                }
                if (entity.AveragePrice == null)
                {
                    entity.AveragePrice = "";
                }
                if (entity.PropertyManagementFee == null)
                {
                    entity.PropertyManagementFee = "";
                }
                if (entity.BuildingClass == null)
                {
                    entity.BuildingClass = "";
                }
                if (entity.DecorationCondition == null)
                {
                    entity.DecorationCondition = "";
                }
                if (entity.PropertyRight == null)
                {
                    entity.PropertyRight = "";
                }
                if (entity.CooperativeHousing == null)
                {
                    entity.CooperativeHousing = "";
                }
                if (entity.DevelopersRules == null)
                {
                    entity.DevelopersRules = "";
                }
                if (entity.AwardDescription == null)
                {
                    entity.AwardDescription = "";
                }
                if (entity.FilingRules == null)
                {
                    entity.FilingRules = "";
                }
                if (entity.BandSawRules == null)
                {
                    entity.BandSawRules = "";
                }
                if (entity.TransactionRules == null)
                {
                    entity.TransactionRules = "";
                }
                if (entity.PriceAdvantage == null)
                {
                    entity.PriceAdvantage = "";
                }
                if (entity.HouseTypeArea == null)
                {
                    entity.HouseTypeArea = "";
                }
                if (entity.LivingFacilities == null)
                {
                    entity.LivingFacilities = "";
                }
                if (entity.SchoolDistrict == null)
                {
                    entity.SchoolDistrict = "";
                }
                if (entity.Transportation == null)
                {
                    entity.Transportation = "";
                }
                if (entity.RegionalDevelopment == null)
                {
                    entity.RegionalDevelopment = "";
                }
                if (entity.Characteristic == null)
                {
                    entity.Characteristic = "";
                }
                if (entity.BrandAdvantage == null)
                {
                    entity.BrandAdvantage = "";
                }
                if (entity.HaveProductComparison == null)
                {
                    entity.HaveProductComparison = "";
                } 
                #endregion
                Buildings bd = BuildingsContract.GetByKey(entity.Id);
                bd.Id = entity.Id;
                bd.Name = entity.Name; 
                bd.Address = entity.Address;
                bd.BuildingTypeID = entity.BuildingTypeID;
                bd.StationedStaffID = entity.StationedStaffID;
                bd.MediumOfCommunicationStaffID = entity.MediumOfCommunicationStaffID;
                bd.CommissionAccount = entity.CommissionAccount;
                bd.SellingPrice = entity.SellingPrice;
                bd.Remark = entity.Remark;
                bd.CreatedTime = entity.CreatedTime;
                bd.IsDeleted = entity.IsDeleted;
                bd.IsLocked = entity.IsLocked;

                bd.LetSellType = 2;
                bd.AreaID = entity.District;
                bd.City = AreaContract.GetByKey(entity.District).ParentID;
                bd.Province = AreaContract.GetByKey(entity.City).ParentID;




                var query = BuildingsContract.CheckExists(m => m.Name.Equals(entity.Name) && m.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的楼盘";
                }
                else
                {  
                    var count = BuildingsContract.Update(bd);
                    BuildingBuildingTypeContract.DeleteDirect(p => p.BuildingID == entity.Id);
                    var Buildings = Request["BuildingTypeID"];
                    foreach (string item in Buildings.Split(','))
                    {
                        BuildingBuildingTypeContract.Insert(new BuildingBuildingType { BuildingID = entity.Id, BuildingTypeID = Convert.ToInt32(item) });
                    }
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion 

        #region 楼盘删除
        [Description("楼盘-列表删除")]
        [HttpPost]
        public ActionResult DeleteListAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                BuildingsContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new Buildings { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion 

        #region 设置结算模式
        /// <summary>
        /// 设置结算模式
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns> 
        [Description("楼盘-设置结算模式")]
        public ActionResult SetStarTarget(int id)
        {

            if (id == 0) throw new Exception("参数错误");
            var entity = BuildingsContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该记录");
            ViewBag.entity = entity;
            return View();
        }
        /// <summary>
        /// 设置结算模式
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditSetStarTarget(Buildings entity)
        {
            var result = new AjaxResult();



            #region 所有string为null的赋值""
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.LeasePrice == null)
            {
                entity.LeasePrice = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.BuildingInfo == null)
            {
                entity.BuildingInfo = "";
            }
            if (entity.SellingBrokerage == null)
            {
                entity.SellingBrokerage = "";
            }
            if (entity.LeaseBrokerage == null)
            {
                entity.LeaseBrokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.AveragePrice == null)
            {
                entity.AveragePrice = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.CooperativeHousing == null)
            {
                entity.CooperativeHousing = "";
            }
            if (entity.DevelopersRules == null)
            {
                entity.DevelopersRules = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.FilingRules == null)
            {
                entity.FilingRules = "";
            }
            if (entity.BandSawRules == null)
            {
                entity.BandSawRules = "";
            }
            if (entity.TransactionRules == null)
            {
                entity.TransactionRules = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            entity.Y = 41.7529445584274;
            entity.X = 123.422754665974;
            #endregion

            try
            {
                var count = BuildingsContract.UpdateDirect(d => entity.Id == d.Id,
                    d => new Buildings { StarTarget = entity.StarTarget, StarTargetRemark = entity.StarTargetRemark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }
        #endregion

        #region 设置在线状态
        /// <summary>
        /// 设置在线状态
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Description("楼盘-设置在线状态")]
        public ActionResult StateSet(int id)
        {

            if (id == 0) throw new Exception("参数错误");
            var entity = BuildingsContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该记录");
            ViewBag.entity = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditStateSet(Buildings entity)
        {
            var result = new AjaxResult();


            #region 所有string为null的赋值""
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.LeasePrice == null)
            {
                entity.LeasePrice = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.BuildingInfo == null)
            {
                entity.BuildingInfo = "";
            }
            if (entity.SellingBrokerage == null)
            {
                entity.SellingBrokerage = "";
            }
            if (entity.LeaseBrokerage == null)
            {
                entity.LeaseBrokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.AveragePrice == null)
            {
                entity.AveragePrice = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.CooperativeHousing == null)
            {
                entity.CooperativeHousing = "";
            }
            if (entity.DevelopersRules == null)
            {
                entity.DevelopersRules = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.FilingRules == null)
            {
                entity.FilingRules = "";
            }
            if (entity.BandSawRules == null)
            {
                entity.BandSawRules = "";
            }
            if (entity.TransactionRules == null)
            {
                entity.TransactionRules = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            entity.Y = 41.7529445584274;
            entity.X = 123.422754665974;
            #endregion

            try
            {
                var count = BuildingsContract.UpdateDirect(d => entity.Id == d.Id, d => new Buildings { State = entity.State });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }
        #endregion

        #region 佣金日志
        /// <summary>
        /// 佣金日志
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns> 
        [Description("楼盘-佣金日志")]
        public ActionResult Commission(int Id)
        {
            IList<string> listTime = new List<string>();
            IList<string> listName = new List<string>();
            IList<string> listSelling = new List<string>();
            var query = ModifyBuildingBrokerageLogContract.TrackEntities.Where(m => !m.IsDeleted && m.BuildingID == Id);
            query = query.OrderByDescending(m => m.Id);
            foreach (var item in query)
            {
                listTime.Add(item.CreatedTime.ToString());
                listName.Add(item.StaffName);
                listSelling.Add(item.SellingBrokerage);
            }
            ViewBag.listTime = listTime;
            ViewBag.listName = listName;
            ViewBag.listSelling = listSelling;

            return View();
        }
        #endregion

        #region 佣金修改
        /// <summary>
        /// 佣金修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Description("楼盘-佣金修改")]
        public ActionResult EditCommission(int id)
        {
            var entity = BuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditCommissionAsync(Buildings entity)
        {
            var result = new AjaxResult();
            ModifyBuildingBrokerageLog mentity = new ModifyBuildingBrokerageLog();

            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            mentity.BuildingID = entity.Id;
            mentity.LeaseBrokerage = "";
            try
            {

                var count = BuildingsContract.UpdateDirect(d => entity.Id == d.Id,
                    d => new Buildings { BandSawBrokerage = entity.BandSawBrokerage, SellingBrokerage = entity.SellingBrokerage, LeaseBrokerage = entity.LeaseBrokerage}); 


                mentity.StaffName = (from staff in StaffContract.TrackEntities where staff.Id == model.Id select staff.Name).FirstOrDefault();
                mentity.BandSawBrokerage = entity.BandSawBrokerage;
                mentity.SellingBrokerage = entity.SellingBrokerage;
                //mentity.LeaseBrokerage = entity.LeaseBrokerage;
                var mcount = ModifyBuildingBrokerageLogContract.Insert(mentity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }
        #endregion 

        #region 楼盘详情
        [Description("楼盘-楼盘详情")]
        public ActionResult EditPropertyDetailsedit(int id)
        {
            var entity = BuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewBag.entity = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditPropertyDetailseditAsync(Buildings entity)
        {
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;

            #region 所有string为null的赋值""
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.LeasePrice == null)
            {
                entity.LeasePrice = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.BuildingInfo == null)
            {
                entity.BuildingInfo = "";
            }
            if (entity.SellingBrokerage == null)
            {
                entity.SellingBrokerage = "";
            }
            if (entity.LeaseBrokerage == null)
            {
                entity.LeaseBrokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.AveragePrice == null)
            {
                entity.AveragePrice = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.CooperativeHousing == null)
            {
                entity.CooperativeHousing = "";
            }
            if (entity.DevelopersRules == null)
            {
                entity.DevelopersRules = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.FilingRules == null)
            {
                entity.FilingRules = "";
            }
            if (entity.BandSawRules == null)
            {
                entity.BandSawRules = "";
            }
            if (entity.TransactionRules == null)
            {
                entity.TransactionRules = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            #endregion

            Buildings bd = BuildingsContract.GetByKey(entity.Id);
            bd.OpeningTime = entity.OpeningTime;
            bd.LaunchTime = entity.LaunchTime;
            bd.Developer = entity.Developer;
            bd.DeveloperBrand = entity.DeveloperBrand;
            bd.PropertyManagementCompany = entity.PropertyManagementCompany;
            bd.CoveredArea = entity.CoveredArea;
            bd.TotalHouseholds = entity.TotalHouseholds;
            bd.PlotRatio = entity.PlotRatio;
            bd.GreeningRatio = entity.GreeningRatio;
            bd.CarNumber = entity.CarNumber;
            bd.ParkingRatio = entity.ParkingRatio;
            bd.AveragePrice = entity.AveragePrice;
            bd.PropertyManagementFee = entity.PropertyManagementFee;  
            bd.BuildingClass = Request["BuildingClass"];
            bd.DecorationCondition = Request["DecorationCondition"];
            bd.PropertyRight = entity.PropertyRight;
            bd.CreatedTime = entity.CreatedTime;
            bd.IsDeleted = entity.IsDeleted;
            bd.IsLocked = entity.IsLocked;

            bd.LetSellType = 2;
            //bd.AreaID = entity.District;
            //bd.City = AreaContract.GetByKey(entity.District).ParentID;
            //bd.Province = AreaContract.GetByKey(entity.City).ParentID;


            try
            {
                var count = BuildingsContract.Update(bd);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 楼盘信息
        [Description("楼盘-楼盘信息")]
        public ActionResult EditPropertyInformationeditData(int id)
        {
            var entity = BuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditPropertyInformationeditDataAsync(Buildings entity)
        {
            var result = new AjaxResult();
             
            try
            { 
                var count = BuildingsContract.UpdateDirect(d => entity.Id == d.Id,d => new Buildings { BuildingInfo = entity.BuildingInfo});
                 
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;   
                    result.Content = "修改成功";
                } 
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 开发商规则
        [Description("楼盘-开发商规则")]
        public ActionResult EditDeveloperRuleeditData(int id)
        {
            var entity = BuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditDeveloperRuleeditDataAsync(Buildings entity)
        {
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;

            #region 所有string为null的赋值""
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.LeasePrice == null)
            {
                entity.LeasePrice = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.BuildingInfo == null)
            {
                entity.BuildingInfo = "";
            }
            if (entity.SellingBrokerage == null)
            {
                entity.SellingBrokerage = "";
            }
            if (entity.LeaseBrokerage == null)
            {
                entity.LeaseBrokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.AveragePrice == null)
            {
                entity.AveragePrice = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.CooperativeHousing == null)
            {
                entity.CooperativeHousing = "";
            }
            if (entity.DevelopersRules == null)
            {
                entity.DevelopersRules = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.FilingRules == null)
            {
                entity.FilingRules = "";
            }
            if (entity.BandSawRules == null)
            {
                entity.BandSawRules = "";
            }
            if (entity.TransactionRules == null)
            {
                entity.TransactionRules = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            #endregion

            Buildings bd = BuildingsContract.GetByKey(entity.Id);
            bd.CooperateBeginTime = entity.CooperateBeginTime;
            bd.SubscriptionDeadline = entity.SubscriptionDeadline;
            bd.DevelopersRules = entity.DevelopersRules;
            bd.BandSawRules = entity.BandSawRules;
            bd.CooperateEndTime = entity.CooperateEndTime;
            bd.CooperativeHousing = entity.CooperativeHousing;
            bd.FilingRules = entity.FilingRules;
            bd.TransactionRules = entity.TransactionRules;
            bd.AwardDescription = entity.AwardDescription;
            bd.CreatedTime = entity.CreatedTime;
            bd.IsDeleted = entity.IsDeleted;
            bd.IsLocked = entity.IsLocked;

            bd.LetSellType = 2;
            //bd.AreaID = entity.District;
            //bd.City = AreaContract.GetByKey(entity.District).ParentID;
            //bd.Province = AreaContract.GetByKey(entity.City).ParentID;




            try
            {
                var count = BuildingsContract.Update(bd);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 买点
        [Description("楼盘-买点")]
        public ActionResult EditBuyingPointeditData(int id)
        {
            var entity = BuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditBuyingPointeditDataAsync(Buildings entity)
        {
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;

            #region 所有string为null的赋值""
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.LeasePrice == null)
            {
                entity.LeasePrice = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.BuildingInfo == null)
            {
                entity.BuildingInfo = "";
            }
            if (entity.SellingBrokerage == null)
            {
                entity.SellingBrokerage = "";
            }
            if (entity.LeaseBrokerage == null)
            {
                entity.LeaseBrokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.AveragePrice == null)
            {
                entity.AveragePrice = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.CooperativeHousing == null)
            {
                entity.CooperativeHousing = "";
            }
            if (entity.DevelopersRules == null)
            {
                entity.DevelopersRules = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.FilingRules == null)
            {
                entity.FilingRules = "";
            }
            if (entity.BandSawRules == null)
            {
                entity.BandSawRules = "";
            }
            if (entity.TransactionRules == null)
            {
                entity.TransactionRules = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            #endregion

            Buildings bd = BuildingsContract.GetByKey(entity.Id);
            bd.PriceAdvantage = entity.PriceAdvantage;
            bd.HouseTypeArea = entity.HouseTypeArea;
            bd.LivingFacilities = entity.LivingFacilities;
            bd.SchoolDistrict = entity.SchoolDistrict;
            bd.Transportation = entity.Transportation;
            bd.RegionalDevelopment = entity.RegionalDevelopment;
            bd.Characteristic = entity.Characteristic;
            bd.BrandAdvantage = entity.BrandAdvantage;
            bd.HaveProductComparison = entity.HaveProductComparison;
            bd.CreatedTime = entity.CreatedTime;
            bd.IsDeleted = entity.IsDeleted;
            bd.IsLocked = entity.IsLocked;

            bd.LetSellType = 2;
            //bd.AreaID = entity.District;
            //bd.City = AreaContract.GetByKey(entity.District).ParentID;
            //bd.Province = AreaContract.GetByKey(entity.City).ParentID;



            try
            {
                var count = BuildingsContract.Update(bd);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        
        #region 户型列表
        [Description("楼盘-户型列表")]
        public ActionResult IndexListOfUnits()
        {
            return View();
        }
        #endregion

        #region 坐标
        [Description("楼盘-坐标")]
        public ActionResult EditMapCoordinate(int id)
        {
            var entity = BuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
        }
        [HttpPost]
        public ActionResult EditMapCoordinateAsync(Buildings entity)
        {  
            var result = new AjaxResult();

            try
            {
                var count = BuildingsContract.UpdateDirect(d => entity.Id == d.Id, d => new Buildings { X = entity.X,Y = entity.Y });

                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        } 
        #endregion

        #region 渠道人员，驻场人员列表
        public void intorcount()
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //渠道人员
            var channel = from s in StaffContract.Entities
                          where StaffRolesContract.Entities.Count(m => m.RoleID == 4 && s.Id == m.StaffID) > 0 && s.AgentID==model.AgentId
                          select new
                          {
                              StaffID = s.Id,
                              StaffName = s.Name,
                          };
            List<SelectListItem> gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            var data = from c in channel
                       select new SelectListItem
                       {
                           Value = c.StaffID + "",
                           Text = c.StaffName
                       };
            gridData.AddRange(data);
            ViewData["channel"] = new SelectList(gridData);
            //驻场人员
            var inThefield = from s in StaffContract.Entities
                             where StaffRolesContract.Entities.Count(m => m.RoleID == 8 && s.Id == m.StaffID) > 0 && s.AgentID == model.AgentId
                             select new
                             {
                                 StaffID = s.Id,
                                 StaffName = s.Name,
                             };
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from c in inThefield
                   select new SelectListItem
                   {
                       Value = c.StaffID + "",
                       Text = c.StaffName
                   };
            gridData.AddRange(data);
            ViewData["inThefield"] = new SelectList(gridData);
            //楼盘类型
            gridData = new List<SelectListItem>();
            data = from dic in BuildingTypeContract.TrackEntities
                   select new SelectListItem
                   {
                       Value = dic.Id + "",
                       Text = dic.Name
                   };
            gridData.AddRange(data);
            ViewBag.BuildingType = new SelectList(gridData);
        }
        #endregion

        #region 多选框
        //添加绑定楼盘类型
        public ActionResult GetBuildingsTypeInsert()
        {
            var list = BuildingTypeContract.Entities.ToList();//楼盘类型ID对应值   
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        //修改绑定楼盘类型
        public ActionResult GetBuildingsTypeEdit(int did)
        {
            var list = from a in BuildingTypeContract.Entities
                       select new
                       {
                           ID = a.Id,
                           Name = a.Name,
                           Number = BuildingBuildingTypeContract.Entities.Count(p => p.BuildingTypeID == a.Id && p.BuildingID == did)
                       };

            return JsonEx(list.ToList(), JsonRequestBehavior.AllowGet);
        }
        //修改绑定建筑类型
        public ActionResult GetBuildingClassEdit()
        {
            var BuildingClass = (from b in BuildingsContract.Entities select b.BuildingClass).FirstOrDefault().Split(',');
            var list = from d in DictionaryContract.Entities.Where(m => m.Name == "BuildingClass")
                       select new
                       {
                           ID = d.Id,
                           Name = d.Value, 
                           Number = BuildingClass.Contains(d.Value) == true ? 1 : 0
                       };
            return JsonEx(list.ToList(), JsonRequestBehavior.AllowGet);
        }
        //修改绑定装修状况
        public ActionResult GetDecorationConditionEdit()
        {
            var DecorationCondition = (from b in BuildingsContract.Entities select b.DecorationCondition).FirstOrDefault().Split(',');
            var list = from d in DictionaryContract.Entities.Where(m => m.Name == "DecorationCondition")
                       select new
                       {
                           ID = d.Id,
                           Name = d.Value,
                           Number = DecorationCondition.Contains(d.Value) == true ? 1 : 0
                       };

            return JsonEx(list.ToList(), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取省属区
        /// <summary>  
        /// 获取省份  
        /// </summary>  
        [AjaxOnly]
       public ActionResult GetProvincelist()
        {
            //获取省份数据   
            var queryResult = AreaContract.TrackEntities.Where(a => a.AreaLevel == 1);
            return JsonEx(queryResult.ToList(), JsonRequestBehavior.AllowGet);
        }
        /// <summary>  
        /// 获取城市  
        /// </summary>  
        /// <param name="pid"></param>  
        /// <returns></returns>  
         [AjaxOnly]
       public ActionResult GetCitylist(string pid)//根据省份ID获取城市  
        {
            pid = pid.Trim();
            var list = AreaContract.TrackEntities.Where(m => m.ParentID.Equals(pid)).ToList();//城市ID对应值  
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        [AjaxOnly]
        /// <summary>  
        /// 获取区
        /// </summary>  
        /// <param name="cid"></param>  
        /// <returns></returns>  
        public ActionResult GetDistrictlist(string cid)//根据城市ID获取区县ID  
        {
            cid = cid.Trim();
            var list = AreaContract.TrackEntities.Where(a => a.ParentID.Equals(cid)).ToList();//区县ID对应值 
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region 置顶
        [Description("楼盘-置顶")]
        public ActionResult EditTopData(int UnionModule,int UnionID,int BuildingTopID)
        {
            ViewBag.UnionModule = UnionModule;
            ViewBag.UnionID = UnionID; 
            if (BuildingTopID != 0)
            {
                var topEntity = BuildingTopContract.GetByKey(BuildingTopID); 
                ViewBag.topEntity = topEntity; 
            }
            else
            {
                var bt = new BuildingTop();
                bt.Id = 0;
                bt.UserID = 0;
                bt.UnionID = UnionID;
                bt.UnionModule = UnionModule;
                bt.BeginTime = DateTime.Now;
                bt.EndTime = DateTime.Now;
                bt.TopType = 0;
                bt.ShowIndex = 1;
                ViewBag.topEntity = bt;
            } 
            return View();
        }
        [HttpPost]
        public ActionResult EditTopDataAsync(BuildingTop entity)
        {
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            if (entity.Id == 0)
            {
                entity.UserID = model.Id;
                //新增
                var count = BuildingTopContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            else
            {
                var BuildingTopModel = BuildingTopContract.GetByKey(entity.Id);
                BuildingTopModel.UserID = model.Id;
                BuildingTopModel.BeginTime = entity.BeginTime;
                BuildingTopModel.EndTime = entity.EndTime;
                BuildingTopModel.TopType = entity.TopType;
                BuildingTopModel.ShowIndex = entity.ShowIndex;
                var count = BuildingTopContract.Update(BuildingTopModel);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            } 

            return JsonEx(result);
        }
        #endregion
    }
}